import { HttpContext } from '@angular/common/http';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { STChange, STColumn, STComponent, STPage } from '@delon/abc/st';
import { STData } from '@delon/abc/st/st.interfaces';
import { XlsxService } from '@delon/abc/xlsx';
import { ALLOW_ANONYMOUS } from '@delon/auth';
import { SFComponent, SFSchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';

import { Api } from '../../../shared/api/api';
import {
  DELETED_STATUS_BADGE,
  DELETED_STATUS_ENUM,
  DEPARTMENT_LEVEL_STATUS_BADGE,
  USER_LABEL_ENUM,
  USER_LABEL_TAG,
  USER_STATUS_BADGE
} from '../../../shared/constant/common-constant';
import { ResponseCode } from '../../../shared/response.code';
import { UserEditComponent } from './user-edit.component';

@Component({
  selector: 'components-user-change',
  template: `
    <div class="modal-header">
      <div class="modal-title">分配客户</div>
    </div>
    <nz-card>
      <st
        #st
        [data]="url"
        [columns]="columns"
        [pi]="page.pi"
        (change)="change($event)"
        [ps]="page.ps"
        [total]="page.total"
        [page]="pagination"
      ></st>
    </nz-card>
    <div class="modal-footer">
      <label nz-checkbox name="agree" (nzCheckedChange)="checkedChange($event)">
        <span>分配协作人（选择协作完成）</span>
      </label>
      <button nz-button type="button" (click)="close()">关闭</button>
      <button nz-button type="submit" nzType="primary" (click)="add()" [disabled]="!account_id" [nzLoading]="http.loading"
        >确定</button
      ></div
    >
  `
})
export class ComponentsUserChangeComponent implements OnInit {
  data: any;
  checkBox = false;
  url = Api.BaseUserListApi;
  account_id: any;
  fenpeiList: any;
  record: any = {};
  customer_id: any = [];
  params: any = {};
  list: any = {
    Sheet1: []
  };
  page: any = {
    data: [],
    pi: 1,
    ps: 10,
    size: 10
  };
  pagination: STPage = {
    front: false,
    pageSizes: [10, 20, 30, 40, 50],
    total: true,
    showSize: true,
    showQuickJumper: true
  };
  userList: any = [];
  customer: any = {
    name: '',
    company_name: '',
    company_address: '',
    phone: '',
    business_scope: '',
    business_style: ''
  };

  @ViewChild('st', { static: true }) st!: STComponent;
  columns: STColumn[] = [
    { title: '编号', index: 'id', type: 'radio' },
    { title: '姓名', index: 'user_name' },
    { title: '手机号', index: 'phone' },
    { title: '地址', index: 'address' },
    { title: '级别', index: 'department_level_id', type: 'badge', badge: DEPARTMENT_LEVEL_STATUS_BADGE },
    { title: '状态', index: 'enable', type: 'badge', badge: USER_STATUS_BADGE }
  ];
  customerList: any = [];
  cooperateReqData: any = {};
  constructor(
    private xlsx: XlsxService,
    private modal: NzModalRef,
    protected http: _HttpClient,
    private msgSrv: NzMessageService,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    this.queryUserList();
    console.log(this.fenpeiList);
    this.cooperateReqData.user_name = localStorage.getItem('user_name');
    this.cooperateReqData.user_id = localStorage.getItem('user_id');
  }

  close() {
    this.modal.destroy();
  }
  save() {
    const customer = this.list.Sheet1;
    console.log(customer);
    for (let i = 0; i < customer.length; i++) {
      const customer1: any = this.customer;
      customer1.name = customer[i][0];
      customer1.company_name = customer[i][1];
      customer1.company_address = customer[i][2];
      customer1.phone = customer[i][3];
      customer1.business_scope = customer[i][4];
      customer1.business_style = customer[i][5];
      this.customerList.push(customer1);
    }
    console.log(this.customerList);
    this.add();
  }
  add() {
    if (this.checkBox) {
      this.addCoopearate();
    } else {
      this.http
        .post(
          Api.BaseUpdateCustomerApi,
          this.customerList,
          {},
          {
            headers: {
              Authorization: 'Bearer dGVzdDp0ZXN0'
            },
            context: new HttpContext().set(ALLOW_ANONYMOUS, true)
          }
        )
        .subscribe((res: any) => {
          if (res && res.code === ResponseCode.SUCCESS) {
            this.msgSrv.success('分配成功');
            this.modal.close(true);
          }
        });
    }
  }
  addCoopearate() {
    for (let i of this.fenpeiList) {
      console.log(i);
      this.cooperateReqData.customer_id = i.id;
      this.cooperateReqData.customer_name = i.name;
      this.http
        .post(
          Api.BaseCooperateAddApi,
          this.cooperateReqData,
          {},
          {
            headers: {
              Authorization: 'Bearer dGVzdDp0ZXN0'
            },
            context: new HttpContext().set(ALLOW_ANONYMOUS, true)
          }
        )
        .subscribe((res: any) => {
          if (res && res.code === ResponseCode.SUCCESS) {
            this.msgSrv.success('添加写作人成功');
            this.modal.close(true);
          } else {
            this.msgSrv.success(res.data);
          }
        });
    }
  }
  queryUserList() {
    const current: number = this.params.current || 1;
    const size: number = this.params.size || 10;
    this.http
      .get(
        Api.BaseUserListApi,
        {
          pi: current,
          ps: size
        },
        { context: new HttpContext().set(ALLOW_ANONYMOUS, true) }
      )
      .subscribe((res: any) => {
        if (res && res.code === ResponseCode.SUCCESS) {
          if (res.data) this.page = res.data;
        }
      });
  }
  search(event: any) {
    if (event) {
    }
  }
  change(e: STChange) {
    if (e.radio.id) {
      this.account_id = e.radio.id;
      this.cooperateReqData.cooperate_user_id = e.radio.id;
      this.cooperateReqData.cooperate_user_name = e.radio.user_name;
      for (let i of this.fenpeiList) {
        this.customerList.push({
          account_id: this.account_id,
          last_flow_up_name: e.radio.user_name,
          id: i.id
        });
      }
    }
    console.log(this.customerList);
  }
  checkedChange(event: any) {
    this.checkBox = event;
    console.log(this.checkBox);
  }
}
